package game_engine.display;

import static org.lwjgl.opengl.GL11.GL_QUADS;
import static org.lwjgl.opengl.GL11.glBegin;
import static org.lwjgl.opengl.GL11.glColor4ub;
import static org.lwjgl.opengl.GL11.glEnd;
import static org.lwjgl.opengl.GL11.glPopMatrix;
import static org.lwjgl.opengl.GL11.glPushMatrix;
import static org.lwjgl.opengl.GL11.glTexCoord2f;
import static org.lwjgl.opengl.GL11.glTranslatef;
import static org.lwjgl.opengl.GL11.glVertex2f;
import game_engine.GameEngine;
import game_engine.core.Vector2f;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;

public class GEUtil {

	
	public static BufferedImage makeColorTransparent(Image image, Color color) {
		ImageIcon icon = new ImageIcon(image);
		BufferedImage dimg = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = dimg.createGraphics();
		g.setComposite(AlphaComposite.Src);
		g.drawImage(image, 0, 0, null);
		g.dispose();
		for (int i = 0; i < dimg.getHeight(); i++) {
			for (int j = 0; j < dimg.getWidth(); j++) {
				if (dimg.getRGB(j, i) == color.getRGB()) {
					dimg.setRGB(j, i, 0x8F1C1C);
				}
			}
		}
		return dimg;
	}
	
	public static BufferedImage makeColorLighter(Image image) {
		ImageIcon icon = new ImageIcon(image);
		BufferedImage dimg = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = dimg.createGraphics();
		g.setComposite(AlphaComposite.Src);
		g.drawImage(image, 0, 0, null);
		g.dispose();
		for (int i = 0; i < dimg.getHeight(); i++) {
			for (int j = 0; j < dimg.getWidth(); j++) {
				dimg.setRGB(j, i,new Color(dimg.getRGB(j, i)).brighter().darker().darker().getRGB()); 
			}
		}
		return dimg;
	}
	
	public static void drawImage(Texture t, int x, int y, int width, int height, int alpha) {
		glPushMatrix();

		// bind to the appropriate texture for this sprite
		t.bind();

		// translate to the right location and prepare to draw
		glTranslatef(x, y, 0);
		
		glColor4ub((byte)alpha, (byte)alpha, (byte)alpha, (byte)alpha);
		
		// draw a quad textured to match the sprite
		glBegin(GL_QUADS);
		{
			glTexCoord2f(0, 0);
			glVertex2f(0, 0);

			glTexCoord2f(0, t.getHeight());
			glVertex2f(0, height);

			glTexCoord2f(t.getWidth(), t.getHeight());
			glVertex2f(width, height);

			glTexCoord2f(t.getWidth(), 0);
			glVertex2f(width, 0);
		}
		glEnd();

		// restore the model view matrix to prevent contamination
		glPopMatrix();
	}
	
	public static Vector2f getCenterFromScreen(float width, float height) {
		Vector2f center = new Vector2f();
		float sWidth = GameEngine.resolution.width;
		float sHeight = GameEngine.resolution.height;
		center.x = (sWidth - width)/2;
		center.y = (sHeight - height)/2;
		return center;
	}
}
